import React, { useState, useEffect } from 'react'
import {
  Row, Col,
  Form, Input,
  Select, DatePicker,
  Button, Table,
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import zhCN from 'antd/es/locale/zh_CN'
import { ConfigProvider } from 'antd';
import TableTitle from './../../components/TableTitle'

// 引入导出按钮组件
import Export from './../../components/Export'


// 引入样式
import myStyle from './CSS/AgencyPayOrder.module.css'
// 引入初始化数据
import {
  merchantNameList,
  orderStatusList,
  callbackStatusList,
  paymentOrderData,
  rowSelection,
  columns,
  // total
} from '../../initData/AgencyPayOrder'

import {
  getPaymentOrder,
  allMerchantList,
  allOrderStatus,
  conditionQueryPaymentOrder
} from './../../API'

const { Option } = Select;
const { RangePicker } = DatePicker;

// 表格筛选列数据
let filterColumnData = [
  { value: 'system_order_number', label: '系统订单号' },
  { value: 'payment_orderID', label: '代付订单ID' },
  { value: 'Merchant_order_number', label: '商户订单号' },
  { value: 'payment_status', label: '代付状态' },
  { value: 'merchant_name', label: '商户名称' },
  { value: 'bank_name', label: '银行名称' },
  { value: 'bank_card_number', label: '银行卡号' },
  { value: 'payee_name', label: '收款人姓名' },
  { value: 'paid_in_amount', label: '实付金额' },
  { value: 'service_charge', label: '手续费' },
  { value: 'deduction_amount', label: '扣除金额' },
  { value: 'receiver', label: '受理人' },
  { value: 'card_dealer', label: '卡商' },
  { value: 'callback_status', label: '回调状态' },
  { value: 'creation_time', label: '创建时间' },
  { value: 'acceptance_time', label: '受理时间' },
  { value: 'Payment_time', label: '代付时间' },
  { value: 'callback_time', label: '回调时间' },
  { value: 'IP', label: 'IP' }
]
let optionsList = [];
filterColumnData.map(item => optionsList.push(item.value))

export default function AgencyPayOrder() {
  // 定义hook 创建的 form 控制实例
  const [searchForm] = Form.useForm();

  const empList = [];
  // 初始状态
  // 初始表格数据
  let [initTableData, setInitTableData] = useState(paymentOrderData)
  // 商户名称
  let [merchantName, setMerchantName] = useState(merchantNameList)
  // 订单状态
  let [orderStatus, setOrderStatus] = useState(orderStatusList)
  // 回调状态
  let [callbackStatus] = useState(callbackStatusList)
  // 数据总条数
  let [total, setTotal] = useState();
  // 每页条数
  let [pageSize, setPageSize] = useState(2);
  // 当前页
  let [current, setCurrent] = useState(1);
  // 交易笔数
  let [
    numberOfTransactions,
    setNumberOfTransactions,
  ] = useState()
  // 交易金额
  let [
    transaction_mount,
    setTransactionMount
  ] = useState()
  // 交易手续费
  let [
    transactionFee,
    setTransactionFee
  ] = useState()
  // 扣除金额
  let [
    deductionAmount,
    setDeductionAmount
  ] = useState()

  // 表格 表头 title
  let [columnsList, setcolumnsList] = useState(columns);
  let [options, setOptions] = useState(optionsList)

  // 当前页和一页显示条数发生改变时调用的函数 page(current), pageSize
  const onChangePageSizeCurrent = (page, pageSize) => {
    console.log(page, pageSize);
    setCurrent(page)
    setPageSize(pageSize)
  }

  /* 处理数据函数 */
  // handleInitTableData 处理调用接口返回的数据
  const handleInitTableData = (data) => {
    // console.log(data);
    let newList = [];
    data.forEach((item, index) => {
      // console.log(item);
      newList.push({
        dfId: item.dfId,
        key: item.dfId,
        system_order_number: item.liuShuiHao,//系统订单号
        payment_orderID: item.dingDanId,//代付订单ID 
        Merchant_order_number: item.liuShuiHao,//商户订单号
        payment_status: item.daiFuZhuangTai,//代付状态
        merchant_name: item.shangHuName,//商户名称 
        bank_name: item.yinHangKa.yinHangName,//银行名称
        bank_card_number: item.yinHangKa.yinHangKaHao,//银行卡号
        payee_name: item.shouKuanRen,//收款人姓名
        paid_in_amount: item.shiFuJinE,//实付金额
        service_charge: item.tiXianShouXvFei,//手续费
        deduction_amount: item.kouChuJinE,//扣除金额
        receiver: item.caoZuoRen,//受理人
        card_dealer: item.kaShangName,//卡商
        callback_status: '未回调',//回调状态
        creation_time: item.createTime,//创建时间
        acceptance_time: item.caoZuoShiJian,//受理时间
        Payment_time: item.daiFuShiJian,//代付时间
        callback_time: '',//回调时间
        IP: '182.148.59.92',//IP
        operation: '',//操作
      })
    });

    return newList
  }
  // fmt 日期格式
  const dateFormat = (fmt, date) => {
    let ret;
    const opt = {
      'Y+': date.getFullYear().toString(), // 年
      'm+': (date.getMonth() + 1).toString(), // 月
      'd+': date.getDate().toString(), // 日
      'H+': date.getHours().toString(), // 时
      'M+': date.getMinutes().toString(), // 分
      'S+': date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp('(' + k + ')').exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
      };
    };
    return fmt;
  }

  // 搜索按钮 searchBtn 点击调用的函数
  const searchBtn = () => {
    // 获取搜索区域 input value值
    let {
      entryTime,  //入单时间
      merchantName, //全部商家
      orderNumber, //系统订单号/代付订单号
      orderStatus, //订单状态
      payee //收款人
    } = searchForm.getFieldsValue()
    orderStatus = orderStatus === '订单状态' ? '' : orderStatus
    merchantName = merchantName === '全部商家' ? '' : merchantName
    entryTime = entryTime ? entryTime.map(item => dateFormat('Y-m-d H:M:S', item._d)).join(' - ') : ''

    // console.log('全部商家', merchantName);
    // console.log('订单状态', orderStatus);
    // console.log(entryTime);

    // 查询指定代付订单接口(搜索)
    conditionQueryPaymentOrder({
      chiKaName: payee,
      daiFuZhuangTai: orderStatus,
      kaShangName: '',
      limit: pageSize,
      liuShuiHao: orderNumber,
      page: current,
      shangHuName: merchantName,
      time: entryTime || '2022-4-4 15:33:20 - 2022-4-20 20:28:23',
    }).then(res => {
      console.log(res);
      if (res.code === 0) {
        // 表格数据
        setInitTableData(handleInitTableData(res.data))
        // 数据总条数
        setTotal(res.count);
      }
    })
  }


  useEffect(() => {
    /* 调用接口 */
    // 查询所有用户列表(商户)
    allMerchantList().then(res => {
      // console.log('用户列表', res);
      // console.log(res.data);
      if (res.code === 200) {
        setMerchantName(res.data)
        // 查询所有订单状态列表
        allOrderStatus().then(res => {
          // console.log('订单状态', res);
          // console.log(res.data); //[{id: 1, status: '未代付'}]
          //  [{ id: 1, status: '未代付' }],
          if (res.code === 200) {
            setOrderStatus(res.data)
          }
        })
      }
    })

    // 查询所有代付订单接口
    getPaymentOrder({
      limit: pageSize,
      page: current
    }).then(res => {
      // console.log(res);
      // 表格数据
      setInitTableData(handleInitTableData(res.data))
      // 数据总条数
      setTotal(res.count);
      // 交易笔数
      setNumberOfTransactions(`5 / 10`)
      // 交易金额
      setTransactionMount(`211 / 522元`)
      // 交易手续费
      setTransactionFee(`0 / 0元`)
      // 扣除金额
      setDeductionAmount(`211 / 522元`)

    })

  }, [current, pageSize])


  return (
    <>
      {/* 搜索区域 */}
      <Row className={myStyle.row_margin}>
        {/* <Col span={24}> */}
        <Form
          name="searchForm"
          form={searchForm}
          layout='inline'
          size='large'
        >
          <Col span={4}>
            <Form.Item name="orderNumber" >
              <Input placeholder="系统订单号/代付订单号" />
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item name="merchantName" initialValue='全部商家'
            >
              <Select>
                <Option value="全部商家">全部商家</Option>
                {/* 动态渲染下拉列表 */}
                {
                  merchantName.map((item, index) => <Option key={index + 1} value={item.name}>{item.name}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item name="orderStatus" initialValue="订单状态">
              <Select>
                <Option value="订单状态">订单状态</Option>
                {/* 动态渲染下拉列表 */}
                {
                  orderStatus.map((item, index) => <Option key={index + 1} value={item.status}>{item.status}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>
          <Col span={7}>
            <Form.Item name="entryTime" label='入单时间'
            >
              <RangePicker
                showTime placeholder={['开始时间', '结束时间']}
              />
            </Form.Item>
          </Col>
          <Col span={2}>
            <Form.Item name="callbackStatus" initialValue="回调状态">
              <Select>
                <Option value="订单状回调状态态">回调状态</Option>
                {/* 动态渲染下拉列表 */}
                {
                  callbackStatus.map(item => <Option key={item.id} value={item.status}>{item.status}</Option>)
                }
              </Select>
            </Form.Item>
          </Col>
          <Col span={2}>
            <Form.Item name="payee" >
              <Input placeholder="收款人" />
            </Form.Item>
          </Col>
          <Col span={2}>
            <Form.Item >
              <Button
                style={{ 'marginRight': '10px' }}
                type="primary"
                icon={<SearchOutlined />}
                onClick={searchBtn}
              >
                搜索
              </Button>
            </Form.Item>
          </Col>
          <Col span={1}>
            <Form.Item >
              <Export data={initTableData} header={columnsList} fileName='file1.xlsx' />
            </Form.Item>
          </Col>
        </Form>
        {/* </Col> */}
      </Row>

      {/* 表格头部信息 */}
      <TableTitle
        optionsList={optionsList}
        filterColumnData={filterColumnData}
        setcolumnsList={setcolumnsList}
        columns={columns}
        useEffect={useEffect}
        options={options}
        empList={empList}
        setOptions={setOptions}
        numberOfTransactions={numberOfTransactions}
        transaction_mount={transaction_mount}
        deductionAmount={deductionAmount}
        transactionFee={transactionFee}
      />

      {/* 表格区域 代付订单数据 */}
      <Row >
        <Col span={24}>
          <ConfigProvider locale={zhCN}>
            <Table
              rowSelection={rowSelection}
              columns={columnsList}
              dataSource={initTableData}
              tableLayout='fixed'
              scroll={{ x: 1300 }}
              bordered
              showSorterTooltip={false}
              pagination={{
                total: total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: total => `共 ${total} 条`,
                pageSizeOptions: [2, 5, 10, 30, 50],
                defaultPageSize: 2,
                pageSize: pageSize,
                current: current,
                onChange: onChangePageSizeCurrent,
                size: "small"
              }}
            >
            </Table>
          </ConfigProvider>
        </Col>
      </Row>
    </ >
  )
}